package com.pp.third.remote.sign;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.*;
import java.util.Map.Entry;

import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class Sha1SignUtil {

    protected final static Logger logger = LoggerFactory.getLogger(Sha1SignUtil.class);
    //微信公众号开发的获取时间戳
    public static String getTimeStamp() {
        return String.valueOf(System.currentTimeMillis() / 1000);
    }

    //创建签名SHA1
    public static Map<String, String> createSHA1Sign(SortedMap<String, String> signParams){
        StringBuffer sb = new StringBuffer();
        Set<Entry<String, String>> es = signParams.entrySet();
        Iterator<Entry<String, String>> it = es.iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> entry = it.next();
            String k = entry.getKey();
            String v = entry.getValue();
            sb.append(k + "=" + v + "&");
            //要采用URLENCODER的原始值！
        }
        String params = sb.substring(0, sb.lastIndexOf("&"));
        System.out.println(params);
        String sha1 = getSha1(params);

        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("queryParams", params);
        resultMap.put("signature", sha1);

        return resultMap;
    }
    //Sha1签名
    public static String getSha1(String str) {
        if (str == null || str.length() == 0) {
            return null;
        }
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(str.getBytes("UTF-8"));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char buf[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (Exception e) {
            logger.error("getSha1 error",e);
            throw new RuntimeException(e.getMessage(), e);
        }
    }


    /**
     * 规范化转换
     * @param sortedParamMap
     * @return
     */
    public static String canonicalize(SortedMap<String, String> sortedParamMap) {
        if (sortedParamMap.isEmpty()) {
            return "";
        }
        StringBuffer buffer = new StringBuffer();
        Iterator<Map.Entry<String, String>> iter = sortedParamMap.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, String> kvpair = iter.next();
            buffer.append(percentEncodeRfc3986(kvpair.getKey()));
            buffer.append("=");
            buffer.append(kvpair.getValue());
            if (iter.hasNext()) {
                buffer.append("&");
            }
        }
        String canonical = buffer.toString();
        return canonical;
    }

    /**
     * Rfc3986</br>
     * 此处建议使用spring的encodeUri方法
     * http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/
     * web/util/UriUtils.html
     *
     * @param s
     * @return
     */
    private static String percentEncodeRfc3986(String s) {
        String out;
        try {
            out = URLEncoder.encode(s, "utf-8").replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
        } catch (UnsupportedEncodingException e) {
            out = s;
        }
        return out;
    }

    public static void main(String[] args) throws Exception {
        String nonce = RandomStringUtils.randomAlphanumeric(6);
        String currentTimeStr = String.valueOf(System.currentTimeMillis());

        SortedMap<String, String> signMap = new TreeMap<String, String>();
        signMap.put("nonce", nonce);
        //signMap.put("opfid", "brURBcnD50iSvajAiXONGKjoxmE");
        signMap.put("uid", "15036403151");
        signMap.put("companyId", "15036403151");
        signMap.put("timestamp", currentTimeStr);
        signMap.put("hideRabbitLogo", "1");
        Map<String, String> resultMap = createSHA1Sign(signMap);
        String url = "https://passport.rabbitpre.com/union-login.html?nonce="
                +nonce
                //+"&opfid=brURBcnD50iSvajAiXONGKjoxmE"
                +"&uid=15036403151"
                +"&companyId=15036403151"
                +"&timestamp="+currentTimeStr
                +"&signature="+resultMap.get("signature")
                +"&hideRabbitLogo=1"
                +"&redirecturl="+percentEncodeRfc3986("https://home.rabbitpre.com/marketing/manager")
                ;

        logger.info(String.format("==url==\n%s", url));

        //signMap.put("secret", secret);
        /*

        15036403151
        1678088384
        //具体post请求参数 使用map填充
        HashMap mapWb = new HashMap();
        mapWb.put("name", "张三");//姓名
        mapWb.put("age", 24);//年龄
        mapWb.put("phoneNumber", "13910010002");//手机号码

        String params = new Gson().toJson(mapWb);
        signMap.put("data", params);
        */
        //logger.info(String.format("==调用接口生成签名使用参数==,%s", new Gson().toJson(signMap)));
       /* String sign = Sha1SignUtil.createSHA1Sign(signMap);
        logger.info(String.format("==生成签名==,%s", sign));
        String url = "https://passport.rabbitpre.com/union-login.html?signature="+sign+"&nonce="+nonce
                +"&opfid=brURBcnD50iSvajAiXONGKjoxmE"
                +"&companyId=15036403151&uid=15036403151&timestamp="+timestamp+"&hideRabbitLogo=1";

        logger.info(String.format("==url==\r\n %s", url));
*/
/*

        //因为生成签名和验证签名 需要双方约定使用同一套工具 所以过程是一致的这里展示生成签名 显得有点多余；
        Boolean check = checkSign(mapWb, signMap, sign);
        if (check) {
            //打印出这一行就是胜利
            log.info(String.format("验证成功 sign:%s", sign));
        }
*/

    }
/*

    //验证签名
    private static Boolean checkSign(Object body, Map<String, Object> signMap, String sign) {
        // 创建一个不进行HtmlEscaping的Gson对象
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        String params = gson.toJson(body);

        //验证签名
        signMap.put("data", params);
        String sign2 = null;
        try {
            sign2 = Sha1SignUtil.sign(signMap);
            if (sign.equals(sign2)) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
*/

}